package com.image.service.Impl;

import com.common.utils.TimeUtils;
import com.common.utils.UploadUtils;
import com.common.utils.VerifyCode;
import com.image.service.ImageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-21 11:07
 * @description
 * @copyright 2021
 */
@Service
public class ImageServiceImpl implements ImageService {

  @Value("${custom.imglocal}")
  private String imglocal;

  @Value("${custom.imgweb}")
  private String imgweb;

  @Autowired private StringRedisTemplate stringRedisTemplate;

  @Override
  public String uploadImage(MultipartFile pic) {
    String filename = pic.getOriginalFilename();
    if (filename != null
        && (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png"))
        && StringUtils.isNotBlank(filename.substring(0, filename.lastIndexOf(".")))) {
      String path = UploadUtils.getUploadPath(filename, "/upload");
      String suffixName = filename.substring(filename.lastIndexOf("."));
      if (!new File(imglocal + path).exists()) {
        new File(imglocal + path).mkdirs();
        String fullname = path + "/" + UUID.randomUUID() + suffixName;
        try {
          pic.transferTo(new File(imglocal + fullname));
        } catch (IOException e) {
          e.printStackTrace();
          throw new RuntimeException("文件路径不存在");
        }
        return imgweb + fullname;
      } else {
        throw new RuntimeException("上传非法文件");
      }
    }

    return null;
  }

  @Override
  public String generateValistr(String token, OutputStream outputStream) {
    VerifyCode code = new VerifyCode();
    code.drawImage(outputStream);

    // TODO: 2021/6/21 生成完验证码之后还需存入redis中，再把token存入list中，再把上一次token弹出来删掉
    try {
      stringRedisTemplate.opsForValue().set(token, code.getCode(), 30, TimeUnit.MINUTES);
      stringRedisTemplate.opsForList().leftPush(TimeUtils.cutTimeStamp(token), token);
      String oldKey = stringRedisTemplate.opsForList().index(TimeUtils.cutTimeStamp(token), -1);
      if (oldKey != null && !oldKey.equals(token)) {
        stringRedisTemplate.delete(token);
        stringRedisTemplate.opsForList().rightPop(TimeUtils.cutTimeStamp(token));
      }
    } catch (Exception e) {
      //redis连接失败，不存入验证码
      e.printStackTrace();
    }

    return code.getCode();
  }

  @Override
  public void deleteValistr(String token) {
    stringRedisTemplate.delete(token);
    stringRedisTemplate.delete(TimeUtils.cutTimeStamp(token));
  }
}
